package org.joy.db2;

import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class Searcher {

    private Map<Integer, List<DocHit>> index;

    public Searcher(Map<Integer, List<DocHit>> index) {
        super();
        this.index = index;
    }

    public List<SearchEntry> search(int[] terms, Double[] tfIdf) {
        HashMap<Integer, MergedDocHits> map =
                new HashMap<Integer, MergedDocHits>();
        for (int i = 0; i < terms.length; i++) {
            List<DocHit> hits = index.get(terms[i]);
            for (DocHit hit : hits) {
                if (map.get(hit.getURLID()) == null) {
                    map.put(hit.getURLID(), new MergedDocHits());
                }
                map.get(hit.getURLID()).addDocHit(hit, tfIdf[i]);
            }
        }
        List<SearchEntry> ret = new LinkedList<SearchEntry>();
        // compute the scores
        for (Integer id : map.keySet()) {
            MergedDocHits hits = map.get(id);
            if (hits.getPos().size() == terms.length) {
                ret.add(new SearchEntry(id, hits));
            }
        }
        Collections.sort(ret);
        return ret;
    }

    public Map<Integer, List<DocHit>> getIndex() {
        return index;
    }
}
